package text.journwy;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DisplayCookie
 */
public class DisplayCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DisplayCookie() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Cookie c1 = new Cookie("userName", "Helen"); 
		Cookie c2 = new Cookie("choice", "music catalog"); 
		c1.setMaxAge(10000);
		response.addCookie(c1); 
		response.addCookie(c2); 
		response.setContentType("text/html"); 
		PrintWriter out = response.getWriter(); out.println("<HTML><HEAD><TITLE>Cookie Test</TITLE>"); 
		out.println("</HEAD><BODY>");
		out.println("The servlet you requested just sent some cookies to you.");
		out.println("Please click the button to see the cookies sent to you.");
		out.println("<BR>"); out.println("<FORM METHOD=POST>");
		out.println("<INPUT TYPE=SUBMIT VALUE=Submit>"); out.println("</FORM>"); out.println("</BODY></HTML>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html"); 
		PrintWriter out = response.getWriter(); 
		out.println("<HTML><HEAD><TITLE>Cookie Test</TITLE>"); 
		out.println("</HEAD><BODY>");
		out.println(5 > 3);
		out.println("Here are the cookies present in your request:"); 
		out.println("<BR>"); out.println("<HR><B>Cookies:</B><BR/>");
		Cookie[] cookies = request.getCookies(); 
		int length = cookies.length; 
		for (int i=0; i<length; i++) {
			Cookie cookie = cookies[i]; out.println("<B>Cookie Name:</B> " + cookie.getName() + "<BR>"); 
			out.println("<B>Cookie Value:</B> " + cookie.getValue() + "<BR>");
		}
		out.println("</BODY></HTML>");
	}

}
